const http = require('http');
const os = require('os');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    // 研发网网络环境 客户端 => 227nginx/ 2.0 => 248nginx/test => 225:9009
    // remoteAddress 是指与当前运行环境产生连接到服务器IP（基于TCP）
    res.write('remoteAddress: ' + req.connection.remoteAddress + '\n'); // 服务端前一层
    res.write('x-forwarded-for: ' + req.headers['x-forwarded-for'] + '\n'); // nginx 如果有配置 这个值就是 客户端IP，IP1，IP2...
    res.write('x-real-ip: ' + req.headers['x-real-ip'] + '\n');
    res.write('currServerIp: ' + getIPAdress() + '\n');
    res.end();
}).listen(9009, '0.0.0.0');
// nginx.conf 解析入下：
// proxy_set_header X-Real-IP $remote_addr; 将 与当前nginx建立连接的服务器IP 放入 X-Real-IP 字段  
// proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 将当前remoteAddr追加到X-Forwarded-Ip中


///获取本机ip///
function getIPAdress() {
    var interfaces = os.networkInterfaces();
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            console.log(alias);
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                return alias.address;
            }
        }
    }
}
// const myHost = getIPAdress();